//
// Created by Galaxy on 2022/4/22.
// Copyright (c) 2022 liuqingyuan. All rights reserved.
//

import Foundation
import Realm
import RealmSwift

class RealmHelper{
    class func configRealm() {
        let dbVersion: UInt64 = 1
        let docPath = FileTool.init().getDocumentPath()
        let dbPath = docPath.appending("/database.realm")
        let config = Realm.Configuration.init(fileURL: URL.init(string: dbPath), inMemoryIdentifier: nil, syncConfiguration: nil, encryptionKey: nil, readOnly: false, schemaVersion: dbVersion, migrationBlock: { migration, oldSchemaVersion in
            // 数据库合并
        }, deleteRealmIfMigrationNeeded: false, shouldCompactOnLaunch: nil, objectTypes: nil, seedFilePath: nil)
        Realm.Configuration.defaultConfiguration = config
        Realm.asyncOpen { result in
            switch result {
            case .failure(let error):
                print("数据库创建失败，错误原因\(error)")
            case .success(_):
                print("数据库创建成功")
            }
        }
    }
    
    class func deleteDb() {
        let docPath = FileTool.init().getDocumentPath()
        let dbPath = docPath.appending("/database.realm")
        FileTool.init().deleteFileWithPath(path: dbPath)
    }
    
    class func getDB() -> Realm {
        let docPath = FileTool.init().getDocumentPath()
        let dbPath = docPath.appending("/database.realm")
        let realmDb = try! Realm(fileURL: URL.init(string: dbPath)!)
        return realmDb
    }
    // 插入
    class func insert(model:Object){
        let realmDB = try! Realm()
        do {
            try realmDB.write{
                realmDB.add(model)
            }
        } catch let error {
            print("插入数据失败,\(error.localizedDescription)")
        }
    }
    // 更新
    class func update(model:Object){
        let realmDB = try! Realm()
        do {
            try realmDB.write{
                realmDB.add(model, update: .modified)
            }
        } catch let error {
            print("更新数据失败，\(error.localizedDescription)")
        }
    }
    
    // 查询
    class func select <T> (objectClass: T, filter: String? = nil) -> [T]{
        
        let defaultRealm = getDB()
        var results : Results<Object>
        
        if filter != nil {
            
            results =  defaultRealm.objects((T.self as! Object.Type).self).filter(filter!)
        }
        else {
            results = defaultRealm.objects((T.self as! Object.Type).self)
        }
        guard results.count > 0 else { return [] }
        var objectArray = [T]()
        for model in results{
            objectArray.append(model as! T)
        }
        return objectArray
    }
    
    class func selectOne <T> (objectClass: T, filter: String? = nil) -> T{
        
        let defaultRealm = getDB()
        var object : Object
        if filter != nil {
            object =  defaultRealm.objects((T.self as! Object.Type).self).filter(filter!).first!
        }else {
            object = defaultRealm.objects((T.self as! Object.Type).self).first!
        }
        return object as! T
    }
    // 排序
    class func select <T> (objectClass: T, filter: String? = nil,orderBys:(keypath:String,ascending:Bool)? = nil) -> [T]{
        let defaultRealm = getDB()
        var results : Results<Object>
        if filter != nil {
            results =  defaultRealm.objects((T.self as! Object.Type).self).filter(filter!)
        }
        else if orderBys != nil{
            results = defaultRealm.objects((T.self as! Object.Type).self).sorted(byKeyPath: orderBys!.keypath, ascending: orderBys!.ascending)
        } else {
            results = defaultRealm.objects((T.self as! Object.Type).self)
        }
        guard results.count > 0 else { return [] }
        var objectArray = [T]()
        for model in results{
            objectArray.append(model as! T)
        }
        return objectArray
    }
    //删除所有数据
    class func deleteAllObject(){
        let defaultRealm = getDB()
        do {
            try defaultRealm.write {
                defaultRealm.deleteAll()
                print("删除所有数据")
            }
        }catch let error{
            print("删除数据失败，\(error.localizedDescription)")
        }
    }
    
    class func deleteObject(model: Object){
        let defaultRealm = self.getDB()
        do {
            try defaultRealm.write {
                defaultRealm.delete(model)
            }
        }catch let error{
            print("删除数据失败，\(error.localizedDescription)")
        }
    }
    
    private static func resultsToObjectList(results: Results<Object>) -> Array<Object> {
        var resultsArray = Array<Object>()
        if results.count > 0 {
            for i in 0...(results.count - 1) {
                resultsArray.append(results[i])
            }
        }
        return resultsArray
    }
}
